<?php
declare (strict_types = 1);

namespace app\common\model;

use think\facade\Cache;

class ShopApply extends Base
{
   protected $name = 'shop_apply';

    public function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')->field('id,code,nickname,photo,mobile');
    }

    public function shop()
    {
        return $this->hasOne(Shop::class, 'id', 'shop_id')->field('id,title');
    }

    public function getExaminesAttr($value, $data)
    {
        $type = [0 => '审核中', 1 => '通过', 2 => '驳回'];
        return $type[$data['examine']];
    }

    public static function _save($param, $logs)
    {
        parent::startTrans();
        try {
            if (!isset($param['examine'])) return ['code' => -1, 'msg' => '请选择审核类型'];

            $info = parent::find($param['id']);
            if ($info->isEmpty()) return ['code' => -1, 'msg' => '审核失败'];
            if ($info->getData('examine') != 0) {
                return ['code' => -1, 'msg' => '此笔记录已审核，请勿重复审核！'];
            }
            if ($param['examine'] == 1) {
                $msg = '通过店铺申请,标识ID【' . $param['id'] . '】会员【' . $info->user->code . '】';
                $upd['is_shop'] = 1;
                $upd['shop_id'] = $param['shop_id'];
                ShopApply::push_store($info->uid,$info); //推店奖
                User::update($upd,['id'=>$info->uid]);
            } else {
                $msg = '驳回店铺申请,标识ID【' . $param['id'] . '】会员【' . $info->user->code . '】';
            }

            $info->examine = $param['examine'];
//            if ($param['examine'] != 2) {
//                $info->reject_msg = $param['reject_msg'];
//            }
            $info->admin_id = $logs['admin']->id;
            $info->admin_name = $logs['admin']->admin_name;
            $info->confirm_time = time();
            $info->save();
            Logs::adds($msg, $logs['admin']->id, $logs['admin']->admin_name);
            parent::commit();
            return ['code' => 1, 'msg' => '已审核'];

        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    //推店奖
    public static function push_store($uid,$shop)
    {
        $user = User::find($uid);
        if($user->parent_id)
        {
            $push_store = Cache::get('system')['push_store'];
            $amount = bcmul((string)$shop->amount, (string)$push_store,2);
            Relation::awardPrizes($user->parent_id,$amount,'推店奖', '+',$uid, 7);
        }


    }
}
